package com.tdam2014.grupo3;

import java.util.ArrayList;

import android.app.Fragment;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.tdam2014.grupo3.adapters.PhotoAdapter;
import com.tdam2014.grupo3.db.DatabaseHelper;
import com.tdam2014.grupo3.db.PhotoDatabaseHelper;
import com.tdam2014.grupo3.entities.Photo;
import com.tdam2014.grupo3.flickr.util.URLUtils;
import com.tdam2014.grupo3.interfaces.PhotoSelectionListener;
import com.tdam2014.grupo3.interfaces.UpdateableUI;
import com.tdam2014.grupo3.tasks.UpdatePhotosListTask;

public class PhotoFragment extends Fragment implements UpdateableUI {
	
	private PhotoSelectionListener photoSelectionListener;
	private PhotoAdapter photoAdapter;
	private TextView emptyView;
	private Menu photoMenu;
	private String photoSetID;
	
	private static final String orderByTitle = DatabaseHelper.colPhotoTitle + " COLLATE NOCASE ASC";
	private static final String orderByDate = DatabaseHelper.colPhotoPosted + " ASC";
	private String order = orderByDate;
	
	private int selectedPosition;

	public PhotoFragment() {
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		setHasOptionsMenu(true);
		
		View rootView = inflater.inflate(R.layout.fragment_photo, container, false);
		return rootView;
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		
		photoSetID = getActivity().getIntent().getStringExtra(PhotoSetActivity.KEY_PHOTO_SET_ID);
		
		ArrayList<Photo> photos = null;
		if(photoSetID != null) {
			photos = new PhotoDatabaseHelper(getActivity().getApplicationContext()).getPhotoList(photoSetID, order);
		}
		
		// Si la cantidad de fotos es 0, actualizar
		
		final GridView photosGrid = (GridView) getView().findViewById(R.id.grvPhotos);
		
		emptyView = (TextView) getActivity().findViewById(R.id.txtEmptyPhotosGrid);
		emptyView.setText(R.string.empty_list_photos);
		photosGrid.setEmptyView(emptyView);
		
		registerForContextMenu(photosGrid);
		
		photoAdapter = new PhotoAdapter(getActivity().getApplicationContext());
		photoAdapter.setPhotoSetID(photoSetID);
		photoAdapter.setPhotos(photos);
		photosGrid.setAdapter(photoAdapter);
		
		photosGrid.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				selectedPosition = position;
				getActivity().openContextMenu(photosGrid);
			}
		});
		
	}
	
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		super.onCreateOptionsMenu(menu, inflater);
		inflater.inflate(R.menu.photos_options, menu);
		this.photoMenu = menu;
		
		if(photoAdapter.getCount() == 0) updatePhotos();
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case android.R.id.home:
		        NavUtils.navigateUpFromSameTask(getActivity());
		        return true;
		        
			case R.id.photosSync:
				updatePhotos();
				return true;
				
			case R.id.photosOrderByTitle:
				if(!order.equals(orderByTitle)) {
					order = orderByTitle;
					ArrayList<Photo> photos = new PhotoDatabaseHelper(getActivity().getApplicationContext()).getPhotoList(photoSetID, order);
					photoAdapter.setPhotos(photos);
					photoAdapter.notifyDataSetChanged();
				}
				return true;
				
			case R.id.photosOrderByDate:
				if(!order.equals(orderByDate)) {
					order = orderByDate;
					ArrayList<Photo> photos = new PhotoDatabaseHelper(getActivity().getApplicationContext()).getPhotoList(photoSetID, order);
					photoAdapter.setPhotos(photos);
					photoAdapter.notifyDataSetChanged();
				}
				return true;
		}
		
		return true;
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
	    MenuInflater inflater = getActivity().getMenuInflater();
	    inflater.inflate(R.menu.photo_context_menu, menu);
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		Photo selectedPhoto = photoAdapter.getItem(selectedPosition);
	    switch (item.getItemId()) {
	        case R.id.photoSeeInBrowser:
	        	String url = URLUtils.getImageUrl(selectedPhoto.getFarm(), selectedPhoto.getServer(), selectedPhoto.getId(), selectedPhoto.getSecret(), URLUtils.NO_SUFFIX);
	        	Intent browserIntent = new Intent(Intent.ACTION_VIEW);
	        	browserIntent.setData(Uri.parse(url));
	        	startActivity(browserIntent);
	            return true;
	        case R.id.photoSeeComments:
	        	photoSelectionListener.onPhotoSelected(selectedPhoto);
	            return true;
	        case R.id.photoShareViaEmail:
	        	String subject = getResources().getString(R.string.share_email_subject);
	        	String body = getResources().getString(R.string.share_email_body)
	        			+ "\n\n"
	        			+ URLUtils.getImageUrl(selectedPhoto.getFarm(), selectedPhoto.getServer(), selectedPhoto.getId(), selectedPhoto.getSecret(), URLUtils.NO_SUFFIX)
	        			+ "\n\n"
	        			+ getResources().getString(R.string.share_email_regards);
	        	String uriText = "mailto:?subject=" + subject + "&body=" + body;
		        Uri uri = Uri.parse(uriText);
		        Intent sendIntent = new Intent(Intent.ACTION_SENDTO);
		        sendIntent.setData(uri);
		        startActivity(Intent.createChooser(sendIntent, getResources().getString(R.string.share_email_send)));
	            return true;
	        default:
	            return super.onContextItemSelected(item);
	    }
	}
	
	public void setPhotoSelectionListener(
			PhotoSelectionListener photoSelectionListener) {
		this.photoSelectionListener = photoSelectionListener;
	}
	
	private void updatePhotos() {
		if(photoSetID != null) {
			UpdatePhotosListTask updatePhotoListTask = new UpdatePhotosListTask(getActivity(), photoSetID, this);
			updatePhotoListTask.execute(photoSetID);
		}
	}

	@Override
	public void onStartUpdate() {
		emptyView.setText(getResources().getString(R.string.updating) + " " + getResources().getString(R.string.photos) + "...");
		
		for(int i = 0; i < photoMenu.size(); i++) {
			photoMenu.getItem(i).setVisible(false);
		}
		getActivity().setProgressBarIndeterminateVisibility(true);
		
		ArrayList<Photo> photos = new ArrayList<Photo>();
		photoAdapter.setPhotos(photos);
		photoAdapter.notifyDataSetChanged();
	}

	@Override
	public void onFinishUpdate() {
		emptyView.setText(getResources().getString(R.string.empty_list_photos));
		
		ArrayList<Photo> photos = new PhotoDatabaseHelper(getActivity().getApplicationContext()).getPhotoList(photoSetID, order);
		photoAdapter.setPhotos(photos);
		photoAdapter.notifyDataSetChanged();
		
		getActivity().setProgressBarIndeterminateVisibility(false);
		for(int i = 0; i < photoMenu.size(); i++) {
			photoMenu.getItem(i).setVisible(true);
		}
	}

	@Override
	public void informError(String error) {
		emptyView.setText(error);
		
		ArrayList<Photo> photos = new PhotoDatabaseHelper(getActivity().getApplicationContext()).getPhotoList(photoSetID, order);
		photoAdapter.setPhotos(photos);
		photoAdapter.notifyDataSetChanged();
		
		getActivity().setProgressBarIndeterminateVisibility(false);
		for(int i = 0; i < photoMenu.size(); i++) {
			photoMenu.getItem(i).setVisible(true);
		}
		
		if(!photos.isEmpty()) Toast.makeText(getActivity(), error, Toast.LENGTH_SHORT).show();
	}
}